from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager


class UserManager(BaseUserManager):
    def create_user(self, account, password=None, **extra_fields):
        if not account:
            raise ValueError('The given account must be set')
        user = self.model(account=account, **extra_fields)
        # user.set_password(password)
        user.password = password
        user.save(using=self._db)
        return user


class User(AbstractBaseUser):
    id = models.BigAutoField(primary_key=True)
    nickname = models.CharField(max_length=255, null=True, blank=True)
    account = models.CharField(max_length=255, unique=True)
    password = models.CharField(max_length=255)
    role = models.CharField(max_length=255, default='user/administrator')
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    ent_user_id = models.CharField(max_length=100, null=True, blank=True, verbose_name='主系统用户id')

    USERNAME_FIELD = 'account'
    REQUIRED_FIELDS = []

    objects = UserManager()

    class Meta:
        db_table = 'user'

    def serialize(self):
        return {
            'id': self.id,
            'nickname': self.nickname,
            'account': self.account,
            'role': self.role,
            'ent_user_id': self.ent_user_id,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }
